import akshare as ak 
import sqlite3 
import pandas as pd
from datetime import datetime,timedelta

STOCK_ZH_A_SPOT = True

def market_data():
    df = pd.DataFrame()
    # 市场快照
    if STOCK_ZH_A_SPOT == True:
        df = ak.stock_zh_a_spot() #TMD什么破代码写的
        with sqlite3.connect('example.db') as conn:
            df.to_sql('stock_zh_a_spot',conn,if_exists='replace',index=False)
    else:
        with sqlite3.connect('example.db') as conn:
            df = pd.read_sql('select * from stock_zh_a_spot order by cast(`成交额` as REAL) desc limit 100',conn)
    # 获取流动性前100的股票
    start_date=(datetime.today() - timedelta(days=30)) 
    for item in df.sort_values(by='成交额',ascending=False).head(100)['代码']:
        item = item[2:]
        hist = ak.stock_zh_a_hist(symbol=item,start_date = start_date.strftime('%Y%m%d')) #日线级别数据
        hist_min = ak.stock_zh_a_hist_min_em(symbol=item,start_date = f'{start_date.strftime('%Y-%m-%d')} 09:32:00',period='30') #30分钟级别数据
        hist_min['股票代码']=item
        with sqlite3.connect('example.db') as conn:
            hist.to_sql('stock_zh_a_hist_daily',conn,if_exists='append',index=False)
            hist_min.to_sql('stock_zh_a_hist_30_min_em',conn,if_exists='append',index=False)


if __name__ == '__main__':
    # STOCK_ZH_A_SPOT = False
    # market_data()
    ...

